package com.fs.system.service.impl;

import com.fs.common.core.pojo.SysDept;
import com.fs.common.core.tree.TreeSelect;
import com.fs.system.mapper.SysDeptMapper;
import com.fs.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class SysDeptServiceImpl implements ISysDeptService {
    @Autowired
    private SysDeptMapper deptMapper;

    @Override
    public List<TreeSelect> selectDeptTreeList(SysDept dept) {
        List<SysDept> sysDepts = deptMapper.selectDeptList(dept);
        return buildDeptTreeSelect(sysDepts);
    }

    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        System.out.println(deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList()));
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }


    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        //新建一个SysDept的List集合
        List<SysDept> returnList = new ArrayList<>();

        //得到所有部门id
        List<Long> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());

        //循环变量部门集合
        for (SysDept dept : depts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) { //如果是顶级节点
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept d) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, d);
        d.setChildren(childList);
        //得到子节点的子节点列表
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0;
    }
    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept d) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        for (SysDept dept : list) {
            if (Objects.nonNull(dept.getParentId()) && dept.getParentId().longValue() == d.getDeptId().longValue())
            {
                tlist.add(dept);
            }
        }
        return tlist;
    }
}